﻿using System;
using System.Data;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;


namespace Dimok.Web.UI {
	public abstract class PageToPDF : Page {
		bool ShowHTML { get { return Request["html"] == null ? false : Convert.ToBoolean(Request["html"]); } }
		protected string HostURL { get { return Request.Url.Scheme + "://" + Request.Url.Host; } }
		public abstract string FileName { get; }
		public PageToPDF() { }
		protected override void OnInit(EventArgs e) {
			base.OnInit(e);
			if (!ShowHTML) PreRenderComplete += new EventHandler(DoPreRender);
		}
		void DoPreRender(object sender, EventArgs e) {
			Response.Clear();
			System.IO.StringWriter stringWrite = new System.IO.StringWriter();
			System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
			RenderControl(htmlWrite);

			string html = Regex.Replace(stringWrite.ToString(), "(<head>)", "$1<base HRef='http://" + Environment.MachineName + (Request.Url.Port == 80 ? "" : ":"+Request.Url.Port) + "'></base>", RegexOptions.IgnoreCase);

			WebSupergoo.ABCpdf6.Doc docNew = new WebSupergoo.ABCpdf6.Doc();
			int pageID = docNew.AddImageHtml(html);

			while (docNew.Chainable(pageID)) {
				docNew.Page = docNew.AddPage();
				pageID = docNew.AddImageToChain(pageID);
			}

			Response.AddHeader("Content-Disposition", "inline; filename=\"" + FileName + ".pdf\"");
			Response.ContentType = Dimok.Images.Enums.GetContentType(docNew.GetData());
			Response.BinaryWrite(docNew.GetData());
			//Response.SuppressContent = true;
			Response.End();
		}
	} 
}
